#!/bin/bash

arg2=$2
DPM_OGG_HOME="/ogg/ogg"

temp_file=/tmp/temp_ogg_output.$$
ogg_output_err_file=/tmp/ogg_output_err_file.$$
ogg_output=/tmp/ogg_output.$$
current_user_home=`cd ~;pwd`
if test -e $current_user_home/.bash_profile
then
source $current_user_home/.bash_profile
else
source  $current_user_home/.profile
fi
touch ${ogg_output_raw_file} ${temp_file} ${ogg_output}

function get_ggsci_info() {
    if echo "info all"|$DPM_OGG_HOME/ggsci >/dev/null 2>&1
    then
	echo 0
    else
        echo 1
    fi
}

if [ `get_ggsci_info` -eq 1 ]    
then
   echo "{"
   #echo "\"result\":\"fail\","
   # echo "[]"
    echo "\"data\":[]"
    echo "}"
    rm -f ${ogg_output_raw_file} ${temp_file} ${ogg_output}
    exit 0
fi

function print_info() {
	ogg_output=$1
	num_of_line=`wc -l ${ogg_output} |awk '{print $1}'`
 
	echo "{"
	#echo "\"result\":\"success\","
	echo "\"data\": ["
	#echo "\"data\":["
	i=1
	for line in `cat ${ogg_output}`
	do
		if [ ${i} -eq ${num_of_line} ]
		then 
			echo "    ${line}"
		else
			echo "    ${line},"
		fi 
		let i+=1 
	done
	echo "]}"
}

function get_group_num() {
	echo "info all"|$DPM_OGG_HOME/ggsci|grep -v GGSCI |grep -v "^$"|sed -n '/^Program/,$p' > ${temp_file}
	while read line 
	do
	if echo $line |grep -w Program > /dev/null
	then
		continue
	else
		if [ -z `echo $line|awk '{print $3}'` ]
		then
			var_group="MGR"
		else
			var_group=`echo $line|awk '{print $3}'`
		fi
		echo "{\"{#OGG_PROCESS}\":\"$var_group\"}" >> ${ogg_output}
	fi
	done  < ${temp_file}
		print_info ${ogg_output}
        rm -f ${ogg_output_err_file} ${temp_file} ${ogg_output}
}

function get_all() {
    echo "info all"|$DPM_OGG_HOME/ggsci|grep -v GGSCI |grep -v "^$"|sed -n '/^Program/,$p' > ${temp_file}
    while read line 
	do
	if echo $line |grep -w Program > /dev/null 
	then 
		continue 
	else 
		var_program=`echo $line|awk '{print $1}'`
	    var_status=`echo $line|awk '{print $2}'`
	    var_time_since_chkpt=`echo $line|awk '{print $5}'`
		if [ -z `echo $line|awk '{print $3}'` ]
		then
			var_group=MGR
		else
			var_group=`echo $line|awk '{print $3}'`
		fi 
		if [ -z `echo $line|awk '{print $4}'` ]
		then
			var_lag_at_chkpt="unknown"
		else
			var_lag_at_chkpt=`echo $line|awk '{print $4}'`
		fi
		if [ -z `echo $line|awk '{print $5}'` ]
		then
			var_time_since_chkpt=""
		else
			var_time_since_chkpt=`echo $line|awk '{print $5}'`
		fi
		if [ "$arg2" == "$var_group" ];then
			echo "{\"program\":\"${var_program}\",\"status\":\"${var_status}\",\"ogg_process\":\"${var_group}\",\"lag_at_check\":\"${var_lag_at_chkpt}\",\"time_since_chkpt\":\"${var_time_since_chkpt}\"}" >> ${ogg_output}
        else
            continue
		fi
	fi
	done < ${temp_file}
	
		num_of_line=`wc -l ${ogg_output} |awk '{print $1}'`
		i=1
		for line in `cat ${ogg_output}`
		do
			if [ ${i} -eq ${num_of_line} ]
			then 
				echo "    ${line}"
			else
				echo "    ${line},"
			fi 
			let i+=1 
		done
        rm -f ${ogg_output_err_file} ${temp_file} ${ogg_output}
}
$1